package dao.impl;

import dao.UserDao;
import model.po.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.DruidUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> getAllUsers() {
        String sql = "select * from `user`";
        List<User> allUser = null;
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        try {
            allUser = queryRunner.query(sql, new BeanListHandler<>(User.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return allUser;
    }

    @Override
    public int deleteUser(User user) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "delete from `user` where `id` = ?";
        int result = 0;
        try {
            result = runner.update(sql, user.getId());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return result;
    }

    @Override
    public List<User> getSearchUser(User user) {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select * from `user` where `nickname` like ?";
        List<User> users = null;
        try {
            users = queryRunner.query(sql, new BeanListHandler<>(User.class), "%" + user.getNickname() + "%");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return users;
    }

    @Override
    public List<String> getUserNameByIds(List<Integer> ids) {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select `nickname` from `user` where `id` = ?";
        List<String> nameList = new ArrayList<>(ids.size());
        try {
            for (Integer id : ids) {
                nameList.add(
                        queryRunner
                                .query(
                                        sql,
                                        resultSet -> resultSet.next() ? resultSet.getString(1) : null,
                                        id));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return nameList;
    }
}
